/*
 Copyright 2009 Google Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
*/

/**
 * Class that describes a site/page.
 * @param {string} secureUrl The secure version of the login page.
 * @param {function} verificationFunction Optional function that will be called
 *   to check if we should redirect to the secureUrl. If this is not provided,
 *   we will always redirect to the secureUrl, regardless of the content of
 *   the page.
 * @constructor
 */
function Site(secureUrl, verificationFunction) {
  this.secureUrl = secureUrl;
  this.verificationFunction = verificationFunction;
}

/**
 * Checks if we should redirect to secureUrl.
 * @return {boolean} Whether or not we should redirect to secureUrl.
 */
Site.prototype.shouldRedirect = function() {
  return (this.verificationFunction == null ||
          this.verificationFunction());
}

/* It would be nice to serialize this data somehow. */
var sites = new Array();
sites['http://twitter.com/login'] = new Site(
  'https://twitter.com/login', null);
sites['http://twitter.com/'] = new Site(
  'https://twitter.com', function() {
      return (document.getElementById('small_signup') != null);
    });
sites['http://www.facebook.com/'] = new Site(
  'https://www.facebook.com', function() {
      return (document.getElementById('pass') != null);
    });
sites['http://www.facebook.com/login.php'] = new Site(
  'https://www.facebook.com/login.php', null);
sites['http://www.couchsurfing.org/login.html'] = new Site(
  'https://www.couchsurfing.org/login.html', null);
sites['http://friendfeed.com/'] = new Site(
  'https://friendfeed.com', null);
sites['http://login.live.com/login.srf'] = new Site(
  'https://login.live.com/login.srf', null);

/* Preserve GET parameters. */
var searchString = document.location.search;
var baseUrl = document.location.href;
if (searchString != '') {
  baseUrl = baseUrl.substr(0, baseUrl.indexOf(searchString));
}

var site = sites[baseUrl];
if (site != null && site.shouldRedirect()) {
  document.location.href = site.secureUrl + searchString;
  return;
}

/* Try to guess if this is a login page, and present the user with some sort
 * of warning. */
var inputElements = document.getElementsByTagName('input');
for (i = 0; i < inputElements.length; i++) {
  if (inputElements[i].getAttribute('type') == 'password') {
    inputElements[i].style.backgroundColor = 'red';
  }
}
